<template>
  <div v-show="loading" class="min-h-100 f-c-c">
    <Loading />
  </div>
  <div v-show="!loading && !showSourceCode" class="h-full overflow-auto pb-50">
    <n-data-table
      ref="table"
      :single-line="false"
      :columns="columns"
      :data="data || []"
      :pagination="paginationReactive"
      :row-key="rowKey"
      :row-props="rowProps"
    />
  </div>
  <div v-show="showSourceCode" class="h-full overflow-auto pb-50">
    <div class="mb-10 flex justify-between items-center">
      <n-button type="primary" @click="returnHistory">返回提交记录</n-button>
      <CopyButton :text="code" pop-msg="复制代码" placement="left" />
    </div>
    <div class="flex px-4 py-10">
      <div class="w-120">正确测试用例ID</div>
        <div>
          {{ correctCaseIds }}
        </div>
    </div>
    <div class="flex items-center px-4 py-10">
      <div class="w-120">错误测试用例ID</div>
      <div
          v-if="wrongcases && wrongcases.length"
          class="flex items-center gap-10 text-18"
      >
        <div v-for="item in wrongcases" :key="item.id" class="f-c-c gap-2">
          <span>{{ item.caseId }}</span>
          <SvgIcon
              icon="tips"
              class="h-18 w-18 cursor-pointer"
              @click="handleShowCase(item.caseId, item.id)"
          />
        </div>
      </div>
    </div>
    <div class="flex px-4 py-10">
      <div class="w-120">详细信息</div>
      <n-input :value="remark" type="textarea" rows="4"></n-input>
    </div>
    <!-- <n-input type="textarea" rows="22" :value="code" /> -->
    <div class="flex-1 overflow-auto h-full">
      <div class="w-120">详细代码</div>
      <Codemirror disabled v-model="code" :extensions="extensions" :tab-size="4" />
    </div>
    <div class="flex px-4 py-10">
      <div class="w-120"></div>
    </div>
  </div>
  <n-modal v-model:show="showCaseModal" size="huge" :bordered="false">
    <div class="relative min-w-370 w-3/4 rounded-10 bg-white px-28 py-16 dark:bg-dark">
      <n-button class="absolute right-24 top-20 rounded" text style="font-size: 24px">
        <SvgIcon icon="close" color="black" @click="handleCloseCaseModal" />
      </n-button>
      <h3 class="text-24 font-normal">查看测试用例</h3>
      <h4 class="py-8 text-18 font-normal">测试用例ID：{{ caseObj?.problemtestcases.id }}</h4>
      <div class="mb-10">
        <div class="flex items-center pb-8">
          <h4>测试用例输入</h4>
        </div>
        <n-input
            type="textarea"
            rows="6"
            placeholder=""
            :value="caseObj?.problemtestcases.input"
        />
      </div>
      <div class="flex flex-wrap gap-16">
        <div class="min-w-200 flex-1">
          <div class="flex justify-between pb-8">
            <div class="flex items-center">
              <h4>测试用例正确输出</h4>
            </div>
            <div>
              显示为ASCII码
              <n-switch v-model:value="asciiActive" size="small" />
            </div>
          </div>
          <n-input
              type="textarea"
              rows="6"
              placeholder=""
              :value="
                asciiActive
                  ? getAscii(caseObj?.problemtestcases.output)
                  : caseObj?.problemtestcases.output
              "
          />
        </div>
        <div class="min-w-200 flex-1">
          <div class="flex items-center pb-8">
            <h4>你的用例输出</h4>
          </div>
          <n-input
              type="textarea"
              rows="6"
              placeholder=""
              :value="
                asciiActive ? getAscii(caseObj?.wrongcases.output) : caseObj?.wrongcases.output
              "
          />
        </div>
      </div>
    </div>
  </n-modal>
</template>

<script setup>
import api from '@/api/user'
import Loading from '@/components/common/Loading.vue'
import { formatDateTime } from '@/utils'
import { PROBLEM_TAB_NAMES } from '@/constant'
import { NButton } from 'naive-ui'
import { useRoute } from 'vue-router'
import { Codemirror } from 'vue-codemirror'
import { cpp } from '@codemirror/lang-cpp'
import { java } from '@codemirror/lang-java'
import CopyButton from '@/components/common/CopyButton.vue'
import SvgIcon from "@/components/common/SvgIcon.vue";

const route = useRoute()
const { examId, problemId } = inject('problem/idsValue', {})
const exam = inject('problem/exam')
const activeTab = inject('problem/activeTab')
const lastSubmittedCodeTime = inject('problem/lastSubmittedCodeTime')
const lastSubmittedResult = inject('problem/lastSubmittedResult')
const canSubmitProblem = inject('problem/canSubmitProblem')

const getCaseHintApi = inject('problem/getCaseHintApi')

const loading = ref(false)
const showSourceCode = ref(false)
const revoked = ref(false)
const showCaseModal = ref(false)
const caseObj = ref(null)

//获取提交记录
const getRecords = async () => {
  try {
    loading.value = true
    const res = await api.getRecords({
      examId: examId,
      problemId: problemId,
    })
    data.value = res.data || []
    console.log(data)
  } catch (err) {
    console.log(err)
  } finally {
    loading.value = false
  }
}
//申请撤销
const addStudentRevokeCode = async () => {
  try {
    loading.value = true
    await api.addStudentRevokeCode({
      examId: examId,
      problemId: problemId,
      solutionId: solutionId.value,
      teacherId: teacherId.value,
      type:type.value,
    })
    $message.success('已提交撤销申请')
  }
  catch (err) {
    console.log(err)
  }
  finally {
      loading.value = false
  }
}
const data = ref(null)
const code = ref(null)
const language = ref(null)
const correctCaseIds = ref(null)
const wrongcases = ref(null)
const remark = ref(null)
const userId = ref(null)
const solutionId = ref(null)
const teacherId = ref(null)
const type = ref(null)
const extensions = ref([])
const columns = [
  {
    title: '序号',
    fixed: 'left',
    width: '50',
    render: (_, index) => {
      return `${data.value.length - index}`
    },
  },
  {
    key: 'submitTime',
    title: '提交时间',
    fixed: 'left',
    width: '150',
    render(row) {
      return formatDateTime(row.submitTime)
    },
  },
  {
    key: 'status',
    title: '运行状态',
    fixed: 'left',
    width: '75',
  },
  {
    key: 'language',
    title: '所用语言',
    fixed: 'left',
    width: '75',
  },
  {
    key: 'score',
    title: '所得分数',
    fixed: 'left',
    width: '75',
  },
  {
    key: 'revoke',
    title: '操作',
    fixed: 'left',
    width: '75',
    render(row) {
      if (row.revoke === true) {
        if(row.revokeStatus==='未审核')
        {
          return [
            h(
                NButton,
                {
                  size: 'small',
                  type: 'tertiary',
                  onClick: (event) => RevokeCommit(event,row),
                },
                {
                  default: () => '撤销',
                }
            ),
          ]
        }
        else{
        return [
          h(
            NButton,
            {
              size: 'small',
              type: 'error',
              onClick: (event) => RevokeCommit(event,row),
            },
            {
              default: () => '撤销',
            }
          ),
        ]}
      }
    },
  },
  {
    key: 'revokeStatus',
    title: '备注',
    fixed: 'left',
    width: '75',
    render(row){
      if(row.revokeStatus==='未审核')
      {return '待审核'}
      if(row.revokeStatus==='拒绝')
      {return '教师拒绝'}
    }
  },
]
//定义分页
// const paginationReactive = reactive({
//   page: 1,
//   pageSize: 10,
//   showSizePicker: true,
//   pageSizes: [10, 50, 100, 150],
//   prefix: () => {
//     return '查询出 ' + data.value.length + '条记录'
//   },
//   onChange: (page) => {
//     paginationReactive.page = page
//   },
//   onUpdatePageSize: (pageSize) => {
//     paginationReactive.pageSize = pageSize
//     paginationReactive.page = 1
//   },
// })
const codeHilight = () => {
  if (['C', 'C++', 'c', 'c++'].includes(language.value)) {
    extensions.value = [cpp()]
  } else if (['Java', 'java'].includes(language.value)) {
    extensions.value = [java()]
  }
  // if (appStore.isDark) {
  //   extensions.value.push(oneDark)
  // }
}
const rowProps = (row) => {
  let style = 'cursor: pointer;'

  // 定义点击事件处理器
  const onClick = () => {
    console.log(row)
    code.value = row.sourceCode
    language.value = row.language
    correctCaseIds.value = row.correctCaseIds
    wrongcases.value = row.wrongcases
    remark.value = row.remark
    if(row.status === 'AC')
    {
      remark.value = 'AC：运行结果正确'
    }
    codeHilight()
    showSourceCode.value = true
  }

  return {
    style,
    onClick,
  }
}
const handleShowCase = (caseId, id) => {
  $dialog.warning({
    title: '查看测试用例',
    content: `查看当前题目的正确测试用例会减少该题相应的得分，但查看同一个测试用例不会重复扣分。
你确认要查看正确的测试用例吗？`,
    positiveText: '确认',
    negativeText: '取消',
    onPositiveClick: async () => {
      if (!exam.value) {
        return
      }
      if (!exam.value.canGetHint) {
        $notification.error('该场考试不允许获取提示')
        return
      }
      showCaseModal.value = true
      try {
        // caseId:问题的用例, id:学生提交后产生的错误测试用例
        const res = await getCaseHintApi(caseId, id)
        caseObj.value = res.data
      } catch (err) {
        console.log(err)
      }
    },
  })
}
const handleCloseCaseModal = () => {
  showCaseModal.value = false
  asciiActive.value = false
  caseObj.value = null
}
const asciiActive = ref(false)
const getAscii = (str) => {
  if (!str) return ''
  let strAscii = '' //用于接收ASCII码
  for (let i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) != 10) {
      if (str.charCodeAt(i) != 13) {
        //将\r过滤掉
        strAscii = strAscii + str.charCodeAt(i) + ' ' //把字符串中的字符一个一个的解码
      }
    } else strAscii = strAscii + str.charCodeAt(i) + '\n'
  }
  return strAscii
}
const RevokeCommit = async (event,row) => {
  showSourceCode.value = false
  event.stopPropagation()
    solutionId.value = row.id
    teacherId.value = row.teacherId
    type.value = row.type
    addStudentRevokeCode()
    getRecords()
    revoked.value = true
}
const returnHistory = async () => {
  showSourceCode.value = false
}
const rowKey = (rowData) => {
  return rowData.id
}

watch(canSubmitProblem, () => {
  //运行结果改变重新加载提交记录
  if(canSubmitProblem.value === false)
  {getRecords()}
})
watch(lastSubmittedResult, () => {
  //运行结果改变重新加载提交记录
  getRecords()
})
watch(lastSubmittedCodeTime, () => {
  //点击提交后重新加载提交记录
  getRecords()
})
watch(activeTab, () => {
  if (
    activeTab.value === PROBLEM_TAB_NAMES.COMMIT_HISTORY &&
    data.value === null &&
    lastSubmittedCodeTime.value != null
  ) {
    //初次加载提交记录
    getRecords()
  }
})
</script>
